package pro.shuangxi.common.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import pro.shuangxi.common.vo.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：mengshx
 * @date ：Created in 2022/8/14 19:34
 * @description：全局异常处理器
 */
@ControllerAdvice
public class ExceptionAdvice {

    public ExceptionAdvice() {
        System.out.println("ExceptionAdvice");
    }

    @ExceptionHandler(Exception.class)
    public void exception(Exception e, HttpServletResponse response) throws IOException {
        e.printStackTrace();
        Result error = Result.ERR("程序错误:" + e.getMessage());
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(error);
        response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(result);
    }

}
